package api

import (
	"fmt"
	"hello/models"

	"github.com/beego/beego/v2/client/orm"
)

type UserController struct {
	BaseController
}

func (c *UserController) Insert() {
	o := orm.NewOrm()
	user := new(models.User)
	user.Name = "lijun"
	user.Age = 29
	// insert data
	o.Insert(user)
	c.Ctx.WriteString("insert user success")
}

func (c *UserController) Select() {
	o := orm.NewOrm()
	user := new(models.User)
	user.Id = 1
	err := o.Read(user)
	if err != nil {
		fmt.Println("读取数据失败")
	}

	fmt.Println("数据：", user)

	c.Ctx.WriteString("select user success")
}

func (c *UserController) SelectOne() {
	id, err := c.GetInt("id")
	if err != nil {
		// fmt.Printf("id必须为数字")
		c.Ctx.WriteString("id必须为数字")
		return
	}
	user := models.GetUserById(id)

	if user == nil {
		fmt.Println("没有读取到数据")
		return
	}

	fmt.Println("数据：", user)

	c.Ctx.WriteString("select user success")
}

func (c *UserController) SelectAll() {
	o := orm.NewOrm()
	// user := new(models.User)
	user := new(models.User)
	qs := o.QueryTable(user)
	var users []models.User
	qs.All(&users)
	// if err != nil {
	// 	fmt.Println("读取数据失败", err.Error())
	// }

	fmt.Println("数据：", users)

	c.Ctx.WriteString("select all user success")
}

func (c *UserController) SelectOneJson() {
	id, err := c.GetInt("id")
	if err != nil {
		// fmt.Printf("id必须为数字")
		c.Ctx.WriteString("id必须为数字")
		return
	}
	user := models.GetUserById(id)

	if user == nil {
		fmt.Println("没有读取到数据")
		return
	}

	fmt.Println("数据：", user)

	c.Data["json"] = user
	c.ServeJSON()
}

func (c *UserController) SelectAllJson() {
	o := orm.NewOrm()
	// user := new(models.User)
	user := new(models.User)
	qs := o.QueryTable(user)
	var users []models.User
	qs.All(&users)
	// if err != nil {
	// 	fmt.Println("读取数据失败", err.Error())
	// }

	fmt.Println("数据：", users)

	c.Data["json"] = users
	c.ServeJSON()
}
